﻿

using HbcServerProcess.Interfaces;
using HbcServerProcess.Models;
using HbcServerProcess.Services;
using IotContract.Dtos.Servers.Process;
using IotContract.Dtos.Servers.Pushs;
using IotContract.Interfaces;
using IotContract.Interfaces.Fmt;
using IotContract.Interfaces.Process;
using IotContract.Models.Jobs;
using IotContract.Models.Process;
using Mapster;
using Newtonsoft.Json;

using System.Collections.Concurrent;
using System.Text.Json;
using XT.Common.Services;

namespace HbcServerProcess;
public class ServerMainProcess : IServerMainProcess
{
    private ILogService _logService;
    private IProcessDataService _processDataService;
    private IRemoteHttpService _remoteHttpService;
    private IEnumerable<IServerProcessHandle> _processes;
    private CancellationTokenSource _cancellationTokenSource;
    public ServerMainProcess(IEnumerable<IServerProcessHandle> handles,ILogService logService,IProcessDataService processDataService,
        IRemoteHttpService remoteHttpService)
    {
        _processes = handles.Where(x => x.ProcessName == ProcessName);
        _logService=logService;
        _processDataService=processDataService;
        _remoteHttpService=remoteHttpService;
    }
    public string ProcessName { get; set; } = HbcServerConst.ProcessName;

    public async Task<bool> Run()
    {
        _cancellationTokenSource = new CancellationTokenSource();

        // 数据调度

        foreach (var process in _processes)
        {
            Task.Factory.StartNew(async (o) =>
            {
                if (o is IServerProcessHandle handle)
                {
                    while (true)
                    {
                        if (_cancellationTokenSource.IsCancellationRequested) break;
                        await handle.ParsingData();
                        await handle.ProcessData();
                        await handle.ProcessOrder();
                        await handle.ProcessWarn();

                        await Task.Delay(200);
                    }

                }
            }, process, _cancellationTokenSource.Token);
        }

        // 远程推送报警状态
        Task.Run(async () =>
        {
            while (true)
            {
                if (_cancellationTokenSource.IsCancellationRequested) return;

                await ProcessRemoteCall();
                await Task.Delay(1000);
            }
        }, _cancellationTokenSource.Token); 
        

        _logService.Log($"{ProcessName} 开始启动");
        return true;
    }

    public async Task<bool> Stop()
    {
        _logService.Log($"{ProcessName} 停止运行");
        _cancellationTokenSource?.Cancel();
        _cancellationTokenSource?.Dispose();

        foreach (var process in _processes)
        {
             process.Stop();
            

        }
        return true;
    }

    /// <summary>
    /// 远程提交
    /// </summary>
    /// <returns></returns>
    private async Task ProcessRemoteCall()
    {
        if (_remoteHttpService.IsRemoteTimeout())
        {
            return;
        }
        var result = _processDataService.EquipStatusQueue.TryDequeue(out var status);
        var result2 = _processDataService.EquipWarnQueue.TryDequeue(out var warn);

        // 堆垛机的报警信息不推
        if (result)
        {
            await _remoteHttpService.CommitEquipStatus(status);
        }

        if (result2)
        {
           var end= await _remoteHttpService.CommitEquipWarn(warn);
            _logService.Log($"推送报警信息 equipNo: {warn.EquipmentNo}, type:{warn.EquipType},code:{warn.ErrCode} {warn.StartTime} {end}");
        }
    }
   
}
